<template>
  <div class="user-update-container">
    <el-card class="update-card">
      <template #header>
        <div class="card-header">
          <span>编辑用户信息</span>
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form
        ref="updateFormRef"
        :model="updateForm"
        :rules="updateRules"
        label-width="100px"
        class="update-form"
      >
        <el-form-item label="用户账号">
          <el-input v-model="updateForm.useraccount" disabled />
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="updateForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="updateForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="updateForm.role" placeholder="请选择用户角色">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="账号状态" prop="status">
          <el-radio-group v-model="updateForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="头像链接" prop="avatar">
          <el-input v-model="updateForm.avatar" placeholder="请输入头像链接（可选）" />
        </el-form-item>
        
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="updateForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            确认修改
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 确认修改对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="确认修改"
      width="400px"
      center
    >
      <div class="confirm-content">
        <el-icon class="confirm-icon" color="#E6A23C">
          <Warning />
        </el-icon>
        <p>确定要修改用户 "{{ updateForm.username }}" 的信息吗？</p>
        <div class="change-summary" v-if="hasChanges">
          <p class="change-title">变更内容：</p>
          <ul class="change-list">
            <li v-for="change in changes" :key="change.field">
              {{ change.label }}: {{ change.oldValue }} → {{ change.newValue }}
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="confirmUpdate">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { getUserUpdateById, updateUserUpdate } from '@/api/user'

export default {
  name: 'UserUpdate',
  components: {
    Warning
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const updateFormRef = ref()
    const loading = ref(false)
    const confirmDialogVisible = ref(false)
    
    // 原始用户数据
    const originalUser = ref({})
    
    // 更新表单
    const updateForm = reactive({
      id: '',
      useraccount: '',
      username: '',
      email: '',
      phone: '',
      role: '',
      status: 1,
      avatar: '',
      remark: ''
    })
    
    // 表单验证规则
    const updateRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: false, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: false, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择账号状态', trigger: 'change' }
      ]
    }
    
    // 计算是否有变更
    const hasChanges = computed(() => {
      return Object.keys(changes.value).length > 0
    })
    
    // 计算变更内容
    const changes = computed(() => {
      const changeList = []
      const fieldLabels = {
        username: '用户名',
        email: '邮箱地址',
        phone: '手机号码',
        role: '用户角色',
        status: '账号状态',
        avatar: '头像链接',
        remark: '备注信息'
      }
      
      for (const key in updateForm) {
        if (key === 'id' || key === 'useraccount') continue
        if (updateForm[key] !== originalUser.value[key]) {
          let oldValue = originalUser.value[key]
          let newValue = updateForm[key]
          
          // 特殊处理状态字段
          if (key === 'status') {
            oldValue = oldValue === 1 ? '启用' : '禁用'
            newValue = newValue === 1 ? '启用' : '禁用'
          }
          
          changeList.push({
            field: key,
            label: fieldLabels[key],
            oldValue: oldValue || '空',
            newValue: newValue || '空'
          })
        }
      }
      
      return changeList
    })
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      const userId = route.params.id
      if (!userId) {
        ElMessage.error('用户ID不存在')
        router.push('/user/info')
        return
      }
      
      loading.value = true
      try {
        const response = await getUserUpdateById(userId)
        if (response.success) {
          const userData = response.data
          // 填充表单
          Object.keys(updateForm).forEach(key => {
            updateForm[key] = userData[key] || ''
          })
          // 保存原始数据
          originalUser.value = { ...userData }
        } else {
          ElMessage.error('获取用户信息失败')
          router.push('/user/info')
        }
      } catch (error) {
        ElMessage.error('获取用户信息失败')
        router.push('/user/info')
      } finally {
        loading.value = false
      }
    }
    
    // 提交表单
    const handleSubmit = () => {
      updateFormRef.value.validate((valid) => {
        if (valid) {
          confirmDialogVisible.value = true
        }
      })
    }
    
    // 确认更新
    const confirmUpdate = async () => {
      loading.value = true
      try {
        const response = await updateUserUpdate(updateForm)
        if (response.success) {
          ElMessage.success('用户信息更新成功')
          confirmDialogVisible.value = false
          // 延迟返回列表页
          setTimeout(() => {
            router.push('/user/info')
          }, 1000)
        } else {
          ElMessage.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新用户详细信息失败:', error)
        console.error('错误响应:', error.response)
        console.error('错误状态码:', error.response?.status)
        console.error('错误消息:', error.response?.data)
        
        let errorMsg = '更新用户信息失败'
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message
        } else if (error.response?.status === 403) {
          errorMsg = '权限不足，无法更新用户信息'
        } else if (error.response?.status === 401) {
          errorMsg = '登录已过期，请重新登录'
        } else if (error.message) {
          errorMsg = error.message
        }
        
        ElMessage.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
    
    // 返回列表
    const goBack = () => {
      router.push('/user/info')
    }
    
    onMounted(() => {
      fetchUserInfo()
    })
    
    return {
      updateFormRef,
      updateForm,
      updateRules,
      loading,
      confirmDialogVisible,
      hasChanges,
      changes,
      handleSubmit,
      confirmUpdate,
      goBack
    }
  }
}
</script>

<style scoped>
.user-update-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.update-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.update-form {
  max-width: 600px;
  margin: 0 auto;
}

.confirm-content {
  text-align: center;
  padding: 20px;
}

.confirm-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.change-summary {
  margin-top: 20px;
  text-align: left;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.change-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.change-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.change-list li {
  padding: 4px 0;
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>